package cn.sw.system.onemany.agg.zhujie;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class MapToBeanConverter {
    private static final Map<Class<?>, PropertyDescriptor[]> descriptorCache = new ConcurrentHashMap<>();

    public static <T> T convert(Map<String, Object> map, Class<T> beanClass) {
        try {
            T bean = beanClass.getDeclaredConstructor().newInstance();

            PropertyDescriptor[] descriptors = descriptorCache.computeIfAbsent(beanClass, cls -> {
                try {
                    return Introspector.getBeanInfo(cls).getPropertyDescriptors();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            });

            for (PropertyDescriptor pd : descriptors) {
                if ("class".equals(pd.getName())) continue;
                Method writeMethod = pd.getWriteMethod();
                if (writeMethod != null && map.containsKey(pd.getName())) {
                    writeMethod.invoke(bean, map.get(pd.getName()));
                }
            }
            return bean;
        } catch (Exception e) {
            throw new RuntimeException("Failed to convert map to bean", e);
        }
}}
